from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import List

mcp = FastMCP("Puma MCP Server")

"""
面向 rubygem-puma 软件的 MCP Server

MCP tools 列表：
1. puma_start_server - 启动 Puma web 服务器
   用途：在指定地址和端口启动 Puma 服务器
   参数：host (str) - 监听地址，port (int) - 监听端口
   返回：统一的 JSON 结构

2. puma_check_response - 验证 Puma 服务器响应
   用途：向运行的 Puma 服务器发送 HTTP 请求并验证响应
   参数：url (str) - 要测试的 URL，expected_content (str) - 期望的响应内容
   返回：统一的 JSON 结构
"""

@mcp.tool()
def puma_start_server(host: str = "0.0.0.0", port: int = 3000) -> dict:
    """启动 Puma web 服务器
    
    参数:
        host: 服务器监听地址，默认 0.0.0.0
        port: 服务器监听端口，默认 3000
        
    返回:
        JSON 结构:
        {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"puma -b tcp://{host}:{port}"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def puma_check_response(url: str = "http://127.0.0.1:3000", expected_content: str = "Hello, Puma!") -> dict:
    """验证 Puma 服务器响应
    
    参数:
        url: 要测试的服务器 URL，默认 http://127.0.0.1:3000
        expected_content: 期望在响应中看到的内容，默认 "Hello, Puma!"
        
    返回:
        JSON 结构:
        {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"curl -s {url}"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        
        # 检查响应是否包含期望的内容
        content_found = expected_content in result.stdout
        
        return {
            "success": result.returncode == 0 and content_found,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()